/*
 * @Descripttion:
 * @Author: liuyu
 * @Date: 2023-12-04 15:44:23
 * @LastEditors: liuyu
 * @LastEditTime: 2023-12-04 15:44:23
 * @FilePath: /app/service/role.js
 */
'use strict';
const Service = require('egg').Service;
const moment = require('moment');
class OrgService extends Service {
  // 获取详情信息
  async show(where) {
    const { app } = this;
    const res = await app.mysql.get('db1').get('role', where);
    return res;
  }
  // 获取角色列表
  async index(columns = [], where = {}, page = '', page_size = '') {
    const { app } = this;
    const options = {
      columns,
      // auth role授权部分排序也要同步调整
      orders: [[ 'role_sort', 'acs' ], [ 'role_id', 'desc' ]],
      where,
    };
    if (page && page_size) {
      options.limit = page_size * 1;
      options.offset = (page - 1) * page_size;
    }
    console.log(options);
    const res = await app.mysql.get('db1').select('role', options);
    return res;
  }

  // 获取角色菜单
  async menuids(role_id) {
    const { app } = this;
    const res = await app.mysql.get('db1').select('role_menu', {
      where: {
        role_id,
      },
    });
    return res.map(item => item.menu_id);
  }

  // 添加
  async create(data) {
    const { app, ctx } = this;
    data.create_time = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');

    const res = await app.mysql.get('db1').beginTransactionScope(async conn => {
      const { menus = [], ...rest } = data;
      const role = await conn.insert('role', rest);
      const roleMenuData = menus.map(val => ({
        role_id: role.insertId,
        menu_id: val,
      }));
      await conn.insert('role_menu', roleMenuData);
      return true;
    }, ctx);
    return res;
  }
  // 修改
  async update(data, where) {
    const { app, ctx } = this;
    data.update_time = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');
    // const res = await this.app.mysql.get('db1').update('role', row, where);
    const res = await app.mysql.get('db1').beginTransactionScope(async conn => {
      const { menus = [], ...rest } = data;
      console.log(menus, {
        ...rest,
        ...where,
      });
      await conn.update('role', rest, {
        where,
      });
      console.log(menus);
      if (menus) {
        await conn.delete('role_menu', {
          role_id: where.role_id,
        });
        const roleMenuData = menus.map(val => ({
          role_id: where.role_id,
          menu_id: val,
        }));
        await conn.insert('role_menu', roleMenuData);
      }
      return true;
    }, ctx);
    return res.affectedRows === 1;
  }
  // 删除
  async delete(id) {
    const res = await this.app.mysql.get('db1').delete('role', { role_id: id });
    return res;
  }
}
module.exports = OrgService;
